from datetime import datetime
from flask import current_app
from flask import request, jsonify
from flask import session

from api_v1 import db
from api_v1.models import Order, House
from api_v1.utils.my_decorators import user_login_data
from api_v1.utils.response_code import RET, ret_map
from . import order_blue


@order_blue.route('/<int:id>', methods=['PUT'])
def status(id):
    """修改状态"""
    # 接受参数：状态
    status = request.form.get('status')
    # 查看订单对象
    order = Order.query.get(id)
    # 修改
    order.status = status
    # 如果是拒单，需要添加原因
    if status == 'REJECTED':
        order.comment = request.form.get('comment')
    # 保存
    order.add_update()

    return jsonify(code=RET.OK)


@order_blue.route('/fd',methods = ['GET'])
@user_login_data
def lorders():
    """作为房东查询订单"""
    uid = session['user_id']

    # 查询当前用户的所有房屋编号
    hlist = House.query.filter(House.user_id== uid)
    hid_list = [house.id for house in hlist]

    # 根据房屋编号查找订单
    order_list = Order.query.filter(Order.house_id.in_(hid_list)).order_by(Order.id.desc())

    # 构造结果
    olist =[order.to_dict() for order in order_list]
    return jsonify(olist=olist)


@order_blue.route('/house/<int:id>')
def booking_house(id):
    """查询指定的房屋信息"""
    try:
        house = House.query.get(id)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(house=house.to_dict())


@order_blue.route("/", methods=["POST"])
@user_login_data
def booking():
    """预定订单"""
    # 1.接受参数
    data = request.form
    house_id = data.get("house_id")
    start_date = data.get("start_date")
    end_date = data.get("end_date")
    start_date = datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.strptime(end_date, '%Y-%m-%d')

    # 2.判断参数是否为空
    if not all([house_id, start_date, end_date]):
        return jsonify(code=RET.NODATA, msg=ret_map[RET.NODATA])

    # 3.数据类型转换
    house_id = int(house_id)

    # 4.判断数据是否有效
    if start_date > end_date:
        return jsonify(code=RET.PARAMERR, msg=ret_map[RET.PARAMERR])

    # 5.数据入库
    try:
        # 根据房屋id号查询字符串
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg=ret_map[RET.DBERR])

    # 创建预定对象
    order = Order()
    order.user_id = session["user_id"]
    order.house_id = house_id
    order.begin_date = start_date
    order.end_date = end_date
    order.days = (end_date - start_date).days + 1
    order.house_price = house.price
    order.amount = order.days * order.house_price

    # 将order对象上传数据库
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg=ret_map[RET.DBERR])

    # 6.返回响应
    return jsonify(code=RET.OK)


@order_blue.route('/', methods=['GET'])
@user_login_data
def orders():
    """作为租客查询订单"""
    uid = session['user_id']
    order_list = Order.query.filter(Order.user_id == uid).order_by(Order.id.desc())
    order_list2 = [order.to_dict() for order in order_list]
    return jsonify(olist=order_list2)